﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace P2PWeb
{
    public static class FormatHelper
    {
        public static string CustomFormat(this object value, string formatString)
        {
            switch (formatString.ToLower())
            {
                case "p":
                    return value.CustomFormatP();
                case "n":
                    return value.CustomFormatN();
                default:
                    throw new NotImplementedException();
            }
        }

        public static string CustomFormatP(this object value)
        {
            string formated = string.Format("{0:P}", value).Replace(" ", "");
            if (formated.IndexOf('.') == -1)
                return formated;
            for (int i = formated.Length - 1; i >= 0; i--)
            {
                if (formated[i] == '%')
                    continue;
                if (formated[i] == '.')
                    return formated.Substring(0, i) + "%";
                if (formated[i] != '0')
                    return formated.Substring(0, i + 1) + "%";

            }
            return formated;
        }

        public static string CustomFormatN(this object value)
        {
            string formated = string.Format("{0:N}", value).Replace(" ", "");
            if (formated.IndexOf('.') == -1)
                return formated;
            for (int i = formated.Length - 1; i >= 0; i--)
            {
                if (formated[i] == '.')
                    return formated.Substring(0, i);
                if (formated[i] != '0')
                    return formated.Substring(0, i + 1);
            }
            return formated;
        }

    }
}